import React, { useEffect, useState } from 'react';
import { connect, Dispatch } from 'umi';
import { ISheetItem } from '@/pages/Analysis/type';
import { ConnectState, IResponse } from '@/models/connect';
import { Card, Empty, Input, message, Tabs, Tree } from 'antd';
// import { PlusOutlined } from '@ant-design/icons';
import { debounce } from 'lodash';

import styles from './style.less';
import { ITreeNode } from '@/pages/data';

const StructureTabel = React.lazy(() => import('./components/StructureTabel'));

// const PreviewTabel = React.lazy(() => import('./components/PreviewTabel'));

interface DatasheetProps {
  dispatch: Dispatch;
  sheetList: Array<ISheetItem>;
  panelsParentList: Array<any>;
  dataRoleList: Array<any>;
  projectId: number
}

const Datasheet: React.FC<DatasheetProps> = (props) => {
  const { sheetList, dispatch, dataRoleList, projectId } = props;
  const [expandedKeys, setExpandedKeys] = useState<Array<string>>([]); // 展开指定的树节点
  const [searchValue, setSearchValue] = useState<string>(''); // 搜索关键词
  const [filterTreeData, setFilterTreeData] = useState<Array<any>>([]); // 关键词过滤后的树形结构数据
  const [selectSheet, setSelectSheet] = useState<ISheetItem | any>({}); // 选中展示的数据表
  const [viewTrees, setViewTrees] = useState<any[]>([]); // 展示的视图树
  useEffect(() => {
    dispatch({
      type: 'sheet/fetchSheetListByProjectId',
      payload: projectId,
      callback: (res: ISheetItem[]) => {
      },
    });
    dispatch({
      type: 'dataRole/fetchRoleList',
    });
  }, []);
  /**
   * 监听接口返回的对象数据并初始化数据
   */
  useEffect(() => {
    if (sheetList && sheetList.length) {
      // 初始化文件夹树形结构
      const folders: ITreeNode[] = sheetList.map(d => ({
        key: d.id,
        value: d.id,
        title: d.name,
        parent: d.parentId,
        isFolder: d.isFolder,
      }));
      const searchFoldersById = (datas: ITreeNode[], pId: any) => {
        const children = datas.filter(v => v.parent === pId);
        if (children) {
          children.map(v => {
            const children1 = searchFoldersById(datas, v.key);
            v.children = children1;
            return v;
          });
        }
        return children;
      };
      const folderTrees = folders.filter((tree: any) => !tree.parent || tree.parent === '').map((root) => {
        root.children = searchFoldersById(folders, root.key);
        return root;
      });
      setViewTrees(folderTrees);
    }
  }, [sheetList]);

  // 获得搜索到的内容节点并展开
  const serach = debounce((value) => {
    setSearchValue(value);
    if (value) {
      viewTrees.map((item) => {
        if (item.children) {
          item.children = item.children.filter((v: any) => v.title.indexOf(value) > -1);
        }
        return item;
      });
      const filterArr = viewTrees.filter((v: any) => v.children.length);
      let expandedArr: Array<string> = [];
      filterArr.forEach((item: any) => {
        expandedArr.push(item.key);
      });
      setExpandedKeys(expandedArr);
      setFilterTreeData(filterArr);
    }
  }, 200);

  // 搜索框输入值变化
  const onSearchChange = (e: any) => {
    e.persist();
    serach(e.target.value);
  };

  // 保存编辑后的数据表
  const saveEditSheet = (data: string) => {
    if (data == null) {
      message.warning('无需保存');
      return;
    }
    dispatch({
      type: 'sheet/saveEditSheet',
      payload: {
        id: selectSheet.id,
        model: JSON.stringify(data),
      },
      callback: (res: IResponse) => {
        const { header } = res;
        if (header.code === 200) {
          message.success('修改成功');

          dispatch({
            type: 'sheet/fetchSheetListByProjectId',
            payload:projectId
          });
        } else {
          message.warning('修改失败');
        }
      },
    });
  };
  const onSelect = (selectedKeys: any, info: any) => {
    setExpandedKeys(selectedKeys);
    if (!info.node.isFolder) {
      setSelectSheet(sheetList.find(v => v.id === selectedKeys[0]));
    }
  };
  return (
    <div className={styles.datasheet}>
      <Card
        bordered={false}
        title={<Input placeholder='搜索数据表' onChange={onSearchChange} allowClear />}
        className={styles.formList}
      >
        <Tree
          treeData={viewTrees}
          onSelect={onSelect}
          expandedKeys={expandedKeys}
          blockNode
        />

        {searchValue && !filterTreeData.length  && (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description='无搜索结果' />
        )}
      </Card>
      <Card
        className={styles.dataWrap}
        title={
          <div>
            {selectSheet.name}
          </div>
        }
      >
        <Tabs
          defaultActiveKey='1'
          onChange={(key) => {
          }}
          type='card'
        >
          <Tabs.TabPane tab='数据表结构' key='1'>
            <React.Suspense fallback={null}>
              <StructureTabel modelDatasource={selectSheet.model} saveSheet={saveEditSheet}
                              permissionList={dataRoleList} sheetId={selectSheet.id} />
            </React.Suspense>
          </Tabs.TabPane>
          <Tabs.TabPane tab='建表语句' key='3'>
            <Input.TextArea rows={10} value={selectSheet.sql} />
          </Tabs.TabPane>
        </Tabs>
      </Card>
    </div>
  );
};
export default connect(({ sheet, dataRole }: ConnectState) => ({
  sheetList: sheet.sheetList,
  panelsParentList: sheet.panelsParentList,
  dataRoleList: dataRole.dataRoleList || [],
}))(Datasheet);
